#include "ring_queue.hpp"
#include <cstdlib>
#include <ctime>
#include <iostream>
#include <pthread.h>
#include <unistd.h>
using namespace std;
void *producers_routine(void *argc)
{
    ring_queue_t<int> *ring_queue = static_cast<ring_queue_t<int> *>(argc);
    while (1)
    {
        int resource = rand() % 100;
        ring_queue->push(resource);
        cout << "线程:" << pthread_self() << " 生产了资源: " << resource << endl;
        usleep(50000);
    }
}
void *consumers_routine(void *argc)
{
    ring_queue_t<int> *ring_queue = static_cast<ring_queue_t<int> *>(argc);
    while (1)
    {
        int resource;
        resource = ring_queue->pop();
        cout << "线程:" << pthread_self() << " 消费了资源: " << resource << endl;
        usleep(100000);
    }
}
int main()
{
#define thread_num 4
    srand(static_cast<unsigned int>(time(static_cast<time_t *>(nullptr))) ^ getpid());
    ring_queue_t<int> ring_queue;
    pthread_t consumers[thread_num];
    pthread_t producers[thread_num];
    for (int i = 0; i < thread_num; i++)
    {
        pthread_create(producers + i, nullptr, producers_routine, static_cast<void *>(&ring_queue));
    }
    for (int i = 0; i < thread_num; i++)
    {
        pthread_create(consumers + i, nullptr, consumers_routine, static_cast<void *>(&ring_queue));
    }
    for (int i = 0; i < thread_num; i++)
    {
        pthread_join(consumers[i], nullptr);
    }
    for (int i = 0; i < thread_num; i++)
    {
        pthread_join(producers[i], nullptr);
    }
    return 0;
}